import axios from "axios";
import { Message } from "element-ui";
import router from "@/router/index.js";
// import store from "@/store/index.js";

axios.defaults.withCredentials = true;
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  headers: { "Content-Type": "application/json;charset=UTF-8" },
  timeout: 1000000, // request timeout
  // responseType: "blob",
});

let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let cancelToken = axios.CancelToken;
let removePending = (ever) => {
  // console.log(ever, pending);
  for (let p in pending) {
    if (pending[p].u === ever.url + "&" + ever.method) {
      //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //把这条记录从数组中移除
    }
  }
};

// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(config);
    if (
      (config.url === "/notice/findNotice" ||
        config.url === "/notice/saveNotice") &&
      process.env.VUE_APP_ENVIRONMENT === "production"
    ) {
      // 公告通知接口——正式环境才调这个路径
      config.baseURL = "https://zlkp.zast.org.cn/api/gg/";
    }
    if (
      config.url !== "/file/uploadFile" &&
      config.url !== "/oss/file/uploadFile"
    ) {
      removePending(config); //在一个ajax发送前执行一下取消操作
      config.cancelToken = new cancelToken((c) => {
        // 用请求地址&请求方式拼接的字符串(生成接口的唯一标识)
        pending.push({ u: config.url + "&" + config.method, f: c });
        // console.log(pending);
      });
    }
    const token = sessionStorage.getItem("token");
    if (token && config.url !== "/admin/loginForBack") {
      config.headers.Authorization = `Bearer ${token}`; // 将token设置成请求头
    }
    // console.log(config);
    // let list = [
    //   "/special/exportSpecial",
    //   "/kxOrders/allExportOrders",
    //   "/kxOrders/exportOrdersList",
    // ];
    if (
      (token &&
        (config.url.indexOf("/special/exportSpecial") != -1 ||
          config.url.indexOf("/kxOrders/allExportOrders") != -1 ||
          config.url.indexOf("/kxOrders/exportOrdersList") != -1 ||
          config.url.indexOf("/appStay/exportUserCount") != -1)) ||
      config.url.indexOf("/kiyoshi/exportExcel") != -1
    ) {
      config.responseType = `blob`; // 文件流的形式需要加这个请求头 (导出题目、导出订单)
    }
    if (
      config.url === "/file/uploadFile" ||
      config.url === "/oss/file/uploadFile" ||
      config.url.indexOf("/activityKind/getPersonList") !== -1 ||
      config.url.indexOf("/activityKind/exportPersonList") !== -1
    ) {
      config.timeout = 1000000;
    }
    return config;
  },
  (error) => {
    console.error(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    removePending(response.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
    const { data } = response;
    if (data.code && data.code === 1001) {
      // store.commit("updateChangePassword", response.config.url); // 跳出弹出密码弹窗
      return Promise.reject("error");
    }
    if (
      response.config.url === "/qrCodeLogin/operateCode" ||
      response.config.url === "/qrLogin/operateCode" ||
      response.config.url === "/qrCodeLogin/getUserDetail" ||
      response.config.url === "/question/importQuestion" ||
      response.config.url === "/kxOrders/findById"
    ) {
      return data;
    } else {
      if (
        data?.code &&
        (data.code === "204" || data.code === "500 INTERNAL_SERVER_ERROR")
      ) {
        Message.error(response.data.message);
        return Promise.reject("error");
      } else {
        return data;
      }
    }
    // if (response.config.url === "/queryFileIds") {
    //   data.data.forEach((item) => {
    //     item.previewPath = `${process.env.VUE_APP_BASE_URL}${item.previewPath}`;
    //   });
    // } else if (response.config.url === "/upload") {
    //   data.data.previewPath = `${process.env.VUE_APP_BASE_URL}${data.data.previewPath}`;
    // }
    // return data;
  },
  (error) => {
    console.error(error); // for debug
    switch (error.response?.status) {
      case 403: // 未登录
        Message.error("身份认证失效，请重新登录");
        sessionStorage.clear();
        router.replace({
          path: "/",
        });
        break;
      default:
        break;
    }

    return Promise.reject(error);
  }
);

export default service;
